﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;

namespace WinFormsApp1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            InitializeWebView();
            webView21.Source = new Uri("https://cyry.jtj.gz.gov.cn:5531/uas/app/person/manage?", UriKind.Absolute);
            //webView21.Source = new Uri("https://www.163.com", UriKind.Absolute);
            webView21.WebMessageReceived += (s, e) => { Console.WriteLine("收到：" + e.WebMessageAsJson); };
           
        }

        private async void InitializeWebView()
        {
             
            // 创建临时目录路径
            string _tempDataPath = Path.Combine(Path.GetTempPath(), "WebView2Private_" + Guid.NewGuid().ToString());

            // 创建环境及控制器选项
            //var environment = await CoreWebView2Environment.CreateAsync();
            //var controllerOptions = environment.CreateCoreWebView2ControllerOptions();
            //controllerOptions.IsInPrivateModeEnabled = true;
            // 创建带选项的环境
            var envOptions = new CoreWebView2EnvironmentOptions
            {
                AdditionalBrowserArguments = "--single-process --disable-gpu",
            };
            var env = await CoreWebView2Environment.CreateAsync(null, _tempDataPath, envOptions);
            var options = env.CreateCoreWebView2ControllerOptions();
            options.IsInPrivateModeEnabled = true;
              
            // 初始化WebView2控件
            await webView21.EnsureCoreWebView2Async(env, options);
            webView21.Tag = _tempDataPath;
            //webView21.Disposed += (p, p2) => { Directory.Delete((p as WebView2)?.Tag + "", recursive: true); };
            //Application.ApplicationExit += (p, p2) => { Directory.Delete(_tempDataPath, recursive: true); };
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //webView21.CoreWebView2.ExecuteScriptAsync("imgReq()");
            //string content3 = File.ReadAllText("supabase.js");
            //webView21.CoreWebView2.ExecuteScriptAsync($"{content3}\r\n\r\n alert('wwwwwwwwwwwwww'+supabase)");
        }


        private void webView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
        {
            byte[] imageBytes = new byte[0];//File.ReadAllBytes("slider.png");
             
            webView21.CoreWebView2.ExecuteScriptAsync("document.writeln(location.href)");
            webView21.CoreWebView2.AddHostObjectToScript("viewCallObj", new ViewCallObj());
            string content = File.ReadAllText("call.js");
            string content2 = File.ReadAllText("opencv.js");
            // string content3 = File.ReadAllText("supabase.js");  不能直接加载，页面加载后用ExecuteScriptAsync可以
            string content3 = File.ReadAllText("axios.js");
            webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync($"{content2}\r\n\r\n {content}");//"document.writeln(\"clear1\")"
            webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync($"{content3}");//"document.writeln(\"clear1\")"

            //webView21.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
            webView21.CoreWebView2.WebResourceRequested += (sender, e) =>
            {
                var uri = e.Request.Uri.ToLower();
                if (uri.EndsWith(".png") || uri.EndsWith(".jpg") || uri.EndsWith(".gif") ||
                    uri.EndsWith(".woff2") || uri.Contains("adservice."))
                {
                    var stream = new MemoryStream(imageBytes);
                    e.Response = webView21.CoreWebView2.Environment.CreateWebResourceResponse(stream, 200, "OK", "Content-Type: image/png");//"Blocked"
                }
                if (uri.EndsWith(".css") || uri.EndsWith(".woff") || uri.EndsWith(".ttf"))
                {
                    e.Response = webView21.CoreWebView2.Environment.CreateWebResourceResponse(
                        new MemoryStream(Encoding.UTF8.GetBytes("")), 200, "OK", "Content-Type: text/css");
                }
            };
        }
    }
}
